package com.taotao.web.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.ApiService.ApiService;
import com.taotao.common.ApiService.HttpClientResult;
import com.taotao.common.JedisService.JedisService;
import com.taotao.web.pojo.Item;

@Service
public class ItemService {
	@Autowired
	ApiService apiService;
	@Autowired
	PropertieService propertieService;
	@Autowired
	public JedisService jedisService;

	public Item queryById(Long itemId) {
		// 先从缓存中获取数据, 有就返回
		if (this.getItemByRedis(itemId) != null) return this.getItemByRedis(itemId);
		try {
			String url = StringUtils.replace(propertieService.TT_MANAGE_ITEM,"{id}", itemId.toString());
			HttpClientResult result = apiService.doGet(url);
			String content = result.getContent();
			Item item = PropertieService.MAPPER.readValue(content, Item.class);
			String itemJson = PropertieService.MAPPER.writeValueAsString(item);
			try {
				// 将数据存到redis缓存中
				String key = StringUtils.replace(propertieService.TAOTAO_WEB_JEDISCACHED_ITEMKEY, "{id}",itemId.toString());
				jedisService.setExpr(key, propertieService.TAOTAO_WEB_JEDISCACHED_ITEMLIVE, itemJson);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return item;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 从缓存中查询
	public Item getItemByRedis(Long itemId) {
		try {
			// 先从缓存中查询
			String key = StringUtils.replace(propertieService.TAOTAO_WEB_JEDISCACHED_ITEMKEY, "{id}",itemId.toString());
			String itemJson = jedisService.get(key);
			if (StringUtils.isNotBlank(itemJson)) {
				// 缓存中找到后直接返回
				return PropertieService.MAPPER.readValue(itemJson, Item.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
